package org.swift.mashup.engine.deployment.mcr;

import org.apache.axis2.Constants;
import org.apache.axis2.context.MessageContext;
import org.swift.mashup.engine.deployment.MessageContextReader;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RestParametersMessageContextReader implements MessageContextReader {
	private static final String ENCODING = "UTF-8";

	private Map<Integer,String> mapRestParamPositionToName = new HashMap<Integer,String>();

	public RestParametersMessageContextReader() {
	}

	public void setRestParameterName(int index, String name) {
		mapRestParamPositionToName.put(index, name);
	}

	@Override
	public Map<String, Object> createParameterMap(MessageContext context) {
		Map<String,Object> paramMap = new HashMap<String,Object>();
		List<String> restParams = (List<String>)context.getOptions().getProperty(Constants.REST_PARAMETERS);

		if ( restParams != null ) {
			for ( int i = 1; i <= restParams.size(); i++ ) {
				String name = mapRestParamPositionToName.get(i);
				String value = restParams.get(i-1);

				if ( value != null ) {
					try {
						value = URLDecoder.decode(value, ENCODING);
					}
					catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}

					if ( name != null ) {
						paramMap.put(name, value);
					}

					if ( i == 1 ) {
						// hardcoded first parameter for backwards-compatibility with mashups that use "___restId_"
						paramMap.put(Constants.REST_ID_KEY, value);
					}
				}
			}
		}

		return paramMap;
	}
}
